<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;

        }

        html,
        body {
            height: 100%;
        }

        .box1 {
            width: 200px;
            height: 200px;
            position: absolute;
            top: 0;
            left: 0;
            cursor: move;
            background: orange;
        }
        .box2 {
            width: 200px;
            height: 200px;
            position: absolute;
            top: 0;
            left: 0;
            cursor: move;
            background: greenyellow;
        }
    </style>
</head>

<body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
        class Drag {
            constructor(ele) {
                this.ele = document.querySelector(ele)
                this.init()
            }
            init() {
                this.down()
                this.up()
                console.log(1);
            }
            down() {
                this.ele.onmousedown = (e) => {
                    
                    let l = e.offsetX
                    let h = e.offsetY
                    console.log(l);
                    console.log(h);
                    this.move(l,h)
                }
            }
            move(l, h) {
                document.onmousemove = (e) => {
                    this.ele.style.left = e.pageX - l + 'px';
                    this.ele.style.top = e.pageY - h + 'px';
                }
            }
            up() {
                document.onmouseup = function () {
                    console.log(4);
                    document.onmousemove = null
                }
            }
        }
        new Drag('.box1')

        class Drag2 extends Drag{
            constructor(ele){
                super(ele)
            }
            move(l,h){
                document.onmousemove=(e)=>{
                    let x=e.pageX-l
                    let y=e.pageY-h
                    if(x<=0){
                        x=0
                    }else if(x>document.body.offsetWidth-this.ele.offsetWidth){
                        x = document.body.offsetWidth - this.ele.offsetWidth
                    }
                    if(y<0){
                        y=0
                    }else if(y>=document.body.offsetHeight - this.ele.offsetHeight){
                        y=document.body.offsetHeight - this.ele.offsetHeight
                    }
                    this.ele.style.left = x + 'px'
                    this.ele.style.top = y + 'px'
                }
            }
        }
        new Drag2('.box2')
    </script>
</body>

</html>